import 'package:flutter/material.dart';

// 自定义迭代器类
class NumberIterator implements Iterator<int> {
  final int max;
  int _current = 0;

  NumberIterator(this.max);

  @override
  int get current => _current;

  @override
  bool moveNext() {
    if (_current < max) {
      _current++;
      return true;
    }
    return false;
  }
}

void main() {
  runApp(const IteratorDemoApp());
}

class IteratorDemoApp extends StatelessWidget {
  const IteratorDemoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Iterator 示例',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const IteratorDemoPage(),
    );
  }
}

class IteratorDemoPage extends StatefulWidget {
  const IteratorDemoPage({super.key});

  @override
  State<IteratorDemoPage> createState() => _IteratorDemoPageState();
}

class _IteratorDemoPageState extends State<IteratorDemoPage> {
  final iterator = NumberIterator(5);
  String log = '迭代器已创建，准备开始迭代\n';
  int? currentValue;

  void _iterate() {
    setState(() {
      if (iterator.moveNext()) {
        currentValue = iterator.current;
        log += '调用 moveNext() 返回 true\n';
        log += '调用 current 获取值: ${iterator.current}\n\n';
      } else {
        log += '调用 moveNext() 返回 false - 迭代结束\n';
        currentValue = null;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Iterator 示例')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '当前值: ${currentValue ?? "未开始"}',
              style: const TextStyle(fontSize: 24),
            ),
            const SizedBox(height: 20),
            ElevatedButton(onPressed: _iterate, child: const Text('下一步')),
            const SizedBox(height: 20),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Text(
                  log,
                  style: const TextStyle(fontFamily: 'monospace', fontSize: 16),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
